package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.hosp.ScheduleQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sun.org.apache.regexp.internal.RE;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @program: yygh_parent
 * @author: Mr.Zhuo
 * @create: 2022-03-12 15:17
 **/
@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    // 更新数据库中的预约数量和可预约数量
    @Override
    public void updateSchedule(Schedule schedule) {

        scheduleRepository.save(schedule);
    }

    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        // 进行赋值
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        Schedule schedule = scheduleRepository.findById(scheduleId).get();

        if (null == schedule) {
            throw new YyghException();
        }

        //获取预约规则信息
        Hospital hospital = hospitalService.findHospitalByHoscode(schedule.getHoscode());
        if (null == hospital) {
            throw new YyghException();
        }
        BookingRule bookingRule = hospital.getBookingRule();
        if (null == bookingRule) {
            throw new YyghException();
        }

        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.findDepartmentByHoscodeDepcode(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        Integer quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());
        //挂号开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        //预约截止时间（就是当前时间加10天之后的都不能挂）
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());
        //当天停止挂号时间
        DateTime stopDayTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopDayTime.toDate());

        return scheduleOrderVo;
    }

    //获取排班详情
    @Override
    public Schedule getById(String id) {
        Schedule schedule = scheduleRepository.findById(id).get();
        String hoscode = schedule.getHoscode();
        // 获取医院名字
        Hospital hospitalByHoscode = hospitalService.findHospitalByHoscode(hoscode);
        Map<String, Object> param = schedule.getParam();
        param.put("hosname", hospitalByHoscode.getHosname());
        // 获取科室名字
        Department department = departmentService.findDepartmentByHoscodeDepcode(hoscode, schedule.getDepcode());
        param.put("depname", department.getDepname());

        return schedule;
    }

    //获取可预约排班数据
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        // 首先我们需要进行日期查询在医院设置的放号周期之内
        Hospital hospital = hospitalService.findHospitalByHoscode(hoscode);
        BookingRule bookingRule = hospital.getBookingRule();

        // 定义一个方法进行日期周期数据查询
        IPage<Date> iPage = this.getListDate(page, limit, bookingRule);
        List<Date> dateList = iPage.getRecords();
        // 进行mongon中的数据查询
        Criteria criteria = Criteria
                .where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);
        Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate")
                        .count().as("doCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"));
        AggregationResults<BookingScheduleRuleVo> bookingScheduleRuleVos = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);

        // 然后获取当前可预约的日期的具体时间
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = bookingScheduleRuleVos.getMappedResults();

        // 判断是否为空
        Map<Date, BookingScheduleRuleVo> bookingScheduleRuleVoMap = null;
        if (!StringUtils.isEmpty(bookingScheduleRuleVoList)) {
            bookingScheduleRuleVoMap
                    = bookingScheduleRuleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }
        List<BookingScheduleRuleVo> bookingScheduleRuleVoArrayList = new ArrayList<>();
        for (int i = 0, size = dateList.size(); i < size; i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = bookingScheduleRuleVoMap.get(date);

            // 判断是否存在当前日期
            if (StringUtils.isEmpty(bookingScheduleRuleVo)) {
                // 不存在
                //然后设置参数
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                // 可预约医生人数
                bookingScheduleRuleVo.setDocCount(0);
                // 可预约的科室
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            // 存在的话
            // 设置日期
            bookingScheduleRuleVo.setWorkDateMd(date);
            bookingScheduleRuleVo.setWorkDate(date);

            // 设置周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            // 判断当前是否是最后一天
            if (i == size - 1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            // 然后判断当前是否是第一天
            if (i == 0 && page == 1) {
                DateTime dateTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
                if (dateTime.isBeforeNow()) {
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoArrayList.add(bookingScheduleRuleVo);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("bookingScheduleList", bookingScheduleRuleVoArrayList);
        map.put("total", iPage.getTotal());

        // 其他参数的设置
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department = departmentService.findDepartmentByHoscodeDepcode(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        map.put("baseMap", baseMap);
        return map;
    }

    private IPage<Date> getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        // 首先我们需要进行判断是否超过当前放号时间
        DateTime dateTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        Integer cycle = bookingRule.getCycle();
        if (dateTime.isBeforeNow()) {
            // 当前已超过放号时间，所以我们为了满足10天的周期，我们需要加一
            cycle++;
        }

        // 进行逐次加一获取周期内所有的时间
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime dateTime1 = new DateTime().plusDays(i);
            String toString = dateTime1.toString("yyyy-MM-dd");
            Date date = new DateTime(toString).toDate();
            dateList.add(date);
        }

        // 因为是分页查询，所以我们必须返回分页之后的数据
        List<Date> dateListVO = new ArrayList<>();
        int begin = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        if (end >= cycle) end = cycle;
        for (int i = begin; i < end; i++) {
            dateListVO.add(dateList.get(i));
        }

        IPage<Date> iPage
                = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, limit, dateList.size());
        iPage.setRecords(dateListVO);
        return iPage;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    @Override
    public void saveSchedule(Map<String, Object> paramOB) {
        // 进行数据转换
        String jsonString = JSONObject.toJSONString(paramOB);
        Schedule schedule = JSONObject.parseObject(jsonString, Schedule.class);

        Schedule scheduleMG = scheduleRepository.findScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        // 然后进行数据判断
        if (!StringUtils.isEmpty(scheduleMG)) {
            schedule.setId(scheduleMG.getId());

            schedule.setUpdateTime(new Date());
            schedule.setCreateTime(scheduleMG.getCreateTime());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);
        } else {
            schedule.setUpdateTime(new Date());
            schedule.setCreateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> list(Integer page, Integer limit, ScheduleQueryVo scheduleQueryVo) {
        // 进行数据排序
        Sort sort = Sort.by(Sort.Direction.ASC, "createTime");
        // 进行分页查询
        PageRequest pageRequest = PageRequest.of(page - 1, limit, sort);

        // 数据转换
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);

        // 创建条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase();

        Example<Schedule> example = Example.of(schedule, matcher);

        // 最后进行数据查询
        Page<Schedule> all = scheduleRepository.findAll(example, pageRequest);
        return all;
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (null != schedule) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    //根据医院编号 和 科室编号 ，查询排班规则数据
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
        HashMap<String, Object> map = new HashMap<>();
        // 1.第一步我们需要根据医院编号和科室编号进行查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        // 2.然后进行聚合查询条件书写
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                // 2.1 我们需要以工作时间为组
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        // 2.3.1 统计出诊人数
                        .count().as("docCount")
                        // 2.3.2 统计总计预约数
                        .sum("reservedNumber").as("reservedNumber")
                        // 2.3.3 统计已经预约数
                        .sum("availableNumber").as("availableNumber"),
                // 2.4 排序条件
                Aggregation.sort(Sort.Direction.ASC, "workDate"),
                // 2.5 分页条件输入
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );

        // 然后进行数据查询
        AggregationResults<BookingScheduleRuleVo> aggregate
                = mongoTemplate.aggregate(
                aggregation, //聚合查询的条件
                Schedule.class, // 查询时的实体类
                BookingScheduleRuleVo.class); // 返回时的实体类
        List<BookingScheduleRuleVo> bookingScheduleRuleVos = aggregate.getMappedResults();


        // 因为mongo中没有提供封装分页查询出来结果包装我们需要额外查询总记录数
        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg,
                        Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();


        // 进行数据处理返回
        bookingScheduleRuleVos.stream().forEach(scheduleRuleVos -> {
            Date workDate = scheduleRuleVos.getWorkDate();
            String week = this.getDayOfWeek(new DateTime(workDate));
            scheduleRuleVos.setDayOfWeek(week);
        });
        map.put("bookingScheduleRuleList", bookingScheduleRuleVos);
        map.put("total", total);

        //获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);
        map.put("baseMap", baseMap);
        return map;
    }

    //根据医院编号 、科室编号和工作日期，查询排班详细信息
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        // 调用方法进行数据转换类型
        Date date = new DateTime(workDate).toDate();
        List<Schedule> list = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, date);
        return list;
    }

    /**
     * 根据日期获取周几数据
     *
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
}
